package com.smh;

import org.junit.jupiter.api.Test;

import javax.swing.tree.TreeNode;
import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author shiminghui
 * @date 2025/2/17 18:30
 * @description: TODO
 */
public class _023_二叉树Z层遍历 {

    @Test
    public void test1() {
        TreeNode<Integer> treeNode = new TreeNode<>(
                new TreeNode<>(
                        new TreeNode<>(4),
                        2,
                        new TreeNode<>(5)
                ),
                1,
                new TreeNode<>(
                        new TreeNode<>(6),
                        3,
                        new TreeNode<>(7)
                )
        );
        zLevelOrder(treeNode);
    }

    // 在层序遍历的基础上，实现Z形遍历。直接在队列里面进行排序
    // 也可以使用两个队列，一个队列进行正常遍历，另一个队列进行头插实现倒序
    private void zLevelOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        ArrayDeque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        int cNum = 1; // 当前层节点数
        int cNumCount = 0; // 下一层节点数
        int c = 1; // 当前层数
        while (!deque.isEmpty()) {
            cNumCount = 0;
            if (c % 2 == 1) {
                for (int i = 0; i < cNum; i++) {
                    TreeNode pop = deque.pollFirst();
                    if (pop.left != null) {
                        deque.addLast(pop.left);
                        cNumCount++;
                    }
                    if (pop.right != null) {
                        deque.addLast(pop.right);
                        cNumCount++;
                    }
                    System.out.print(pop.val + " ");
                }
            } else {
                for (int i = 0; i < cNum; i++) {
                    TreeNode pop = deque.pollLast();
                    if (pop.right != null) {
                        deque.addFirst(pop.right);
                        cNumCount++;
                    }
                    if (pop.left != null) {
                        deque.addFirst(pop.left);
                        cNumCount++;
                    }
                    System.out.print(pop.val + " ");
                }
            }
            System.out.println();
            c++;
            cNum = cNumCount;
        }
    }


    private static class TreeNode<T> {
        T val;
        TreeNode left;
        TreeNode right;

        TreeNode(T x) {
            val = x;
        }

        TreeNode(TreeNode left, T x, TreeNode right) {
            this.left = left;
            val = x;
            this.right = right;
        }

        TreeNode() {

        }
    }


}
